package com.i2863.receiptinterface.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2018/6/8.
 */
public class Md5Util {
    public static MessageDigest md = null;

    static{
        try {
            md=MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * md5 32位加密
     * @param plainText 源码
     * @return  md5加密
     */
    public static String encrypt(String plainText) {
        if(plainText==null || plainText.length()<=0){
            throw new IllegalArgumentException("illegal plain text!");
        }
        md.update(plainText.getBytes());
        byte[] b = md.digest();
        int i=0;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }
        //32位加密
        return buf.toString();
        // 16位的加密
        //return buf.toString().substring(8, 24);
    }

    public static void main(String[] args) {
        System.out.println(encrypt("张三"));
    }
}
